<?php
/**
 * Simple Light PHP Framework
 *
 * @copyright Marc PEPIN 2012
 * @author Marc PEPIN
 *
 */

defined('SLP_ROOT') or die("You've not access to this page");
 
/**
 * Simple Light Php Framework Application Common Class
 *
 * It's the class that every library in
 * Simple Light Php will be assigned to.
 *
 * @package             Slp
 * @author              Marc PEPIN
 */
 
 class Slp_Common {
	 
	 
	/**
	* Template shortcut
	* @param string
	* @param array()
	*/
	
	public function theme($template, $vars = NULL) {
		$tpl = Slp::getInstance()->loadClass('Slp_Template', array($template));
		$tpl->assign($vars);
		return $tpl->render();
	}
	
	
	/**
	* Set HTTP Header to json
	* @param mixed
	*/
	
	public function json_output($data) {
        ob_clean();
        header('Content-type: application/json');
        echo json_encode($data);
        exit();
	}
	
	
	/**
	* Error 404
	*/
	
	public function error404() {
		$tpl = Slp::getInstance()->loadClass('Slp_Template', array('ERROR_404'));
		header('HTTP/1.0 404 Not Found');
		$tpl->assign(array('error_msg' => $msg));
		return $tpl->render();
	}
	
	
	/**
	* Base Url
	*/
	
	public function baseUrl() {
		$protocol = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
		$base_url = $protocol . '://' . $_SERVER['HTTP_HOST'];
		if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
		  $base_path = $dir;
		  $base_url .= $base_path;
		  $base_url .= '/';
		}
		else
		  $base_path = '/';
		return $base_url;

	}
	
	
	/**
	* Base Url
	* @param string
	* @param bool
	*/
	
	public function url($path = NULL, $assets = false) {
		if (empty($path))
			return $this->baseUrl();
		if ($assets)
			return $this->baseUrl().$path;
		if (Slp::getInstance()->loaded->Slp_Config->get("urlRewriting"))
            $url = $this->baseUrl().$path;
        else
       		$url = $this->baseUrl().'?q='.$path;
		return $url;

	}
 
	
	/**
	* Redirect to url
	* @param string
	* @param bool
	*/
	
	public function redirect($url, $external = false){
		if ($external != true)
			$url = $this->url($url);	
		header('Location: ' . $url, TRUE, 302);

	}
	
	
	public function arrayKeyRevert(&$array) {
		$tmp = $array;
		foreach ($tmp as $key => $value) {
			$tmp[$value] = $key;	
			unset($tmp[$key]);
		}	
		$array = $tmp;
	}
	/**
	* format string
	* @param string
	* @param array
	*/
	
	public function format($str, $values = array()) {
		foreach($values as $pattern => $replace) 
			$str = preg_replace("!($pattern)!", $replace, $str);
		
		return $str;
	}
 }
 ?>